package com.logicwin.aibala;

import com.logicwin.aibala.utils.StringUtils;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.telephony.TelephonyManager;
import android.util.Log;

public class Aibala extends Application {
    private static Aibala instance;
    private static PackageManager packageManager;
    private static String packageName;
    private static String deviceURN;

    public Aibala() {
    	Aibala.instance = this;
    }

    public static Context getContext() {
        return Aibala.instance;
    }
    
    @Override
	public void onCreate() {
		super.onCreate();
		
		Aibala.packageManager = Aibala.instance.getPackageManager();    		
		Aibala.packageName = Aibala.instance.getPackageName();
	}
    
	public static int getVersionCode(){
    	if(Aibala.packageManager != null){
    		try {
				return Aibala.packageManager.getPackageInfo(Aibala.packageName, 0).versionCode;
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
    	}
    	return 0;
    }
    
    public static String getVersionName(){
    	if(Aibala.packageManager != null){
    		try {
				return Aibala.packageManager.getPackageInfo(Aibala.packageName, 0).versionName;
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
    	}
    	return "0.0";
    }
    
    public static String getDeviceURN(){
    	if(StringUtils.isNullOrEmpty(Aibala.deviceURN)){
	    	try{
		    	TelephonyManager telephonyMgr = (TelephonyManager) Aibala.getContext().getSystemService(Context.TELEPHONY_SERVICE);
		        String msisdn = telephonyMgr.getLine1Number();
		        if(msisdn == null){
		        	Aibala.deviceURN = String.format("urn:imei:%s", telephonyMgr.getDeviceId());
		        }
		        else{
		        	Aibala.deviceURN = String.format("urn:tel:%s", msisdn);
		        }
	    	}
	    	catch(Exception e){
	    		Log.d("org.doubango.imsdroid", e.toString());
	    		Aibala.deviceURN = "urn:uuid:3ca50bcb-7a67-44f1-afd0-994a55f930f4";
	    	}
    	}
    	return Aibala.deviceURN;
    }
}
